﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using WPay.Application.Interface.OAuth;
using WPay.Application.MainModule.OAuth;
using WPay.Infrastructure.IOC;
using Microsoft.OpenApi.Models;
using Microsoft.Extensions.PlatformAbstractions;
using System.IO;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using AutoMapper;
using Microsoft.AspNetCore.Http;
using WPay.Infrastructure.Unity;
using WPay.Infrastructure.EFCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http.Features;
using CommonUtility;

namespace WPay.Web.API
{
    /// <summary>
    /// 系统启动服务配置管理类
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        private IConfiguration Configuration { get; }

        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// 此方法由运行时调用。使用此方法将服务添加到容器
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {


            //添加httpcontext类
            services.AddHttpContextAccessor();
            MvcContext.Configure(services.BuildServiceProvider().GetRequiredService<IHttpContextAccessor>());
            services.AddControllers();
            //添加日志记录
            LoggerHelper.UseLocalLog(services);
            //添加对AutoMapper的支持
            //services.AddAutoMapper(typeof(Startup));
            //添加依赖注入
            services.RegisterAssembly();
            // 添加全局身份验证过滤器
            services.AddControllers(options =>
            {
                options.Filters.Add<ApiAuthorize>();
                options.EnableEndpointRouting = false;
            });
            //添加API版本控制
            services.AddApiVersion();
            //添加对于 swagger 文档的支持
            services.AddSwagger();
            //添加跨域支持
            services.AddCors(option => option.AddPolicy("AllowCors", bu => bu.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
            services.Configure<FormOptions>(x =>
            {
                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
            });
            //var connection = "Server=wuaio-wpaydp.cluster-crdgwrchybgr.rds.cn-northwest-1.amazonaws.com.cn;Port=3306;Database=wpaydp; User=hfl;Password=x60RZJ0W%Ey;";
            //services.AddDbContextPool<Entities>(options => options.UseMySql(connection));
        }

        /// <summary>
        ///  This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        ///  此方法由运行时调用。使用此方法配置HTTP请求管道。 
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="provider"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApiVersionDescriptionProvider provider, IHttpContextAccessor accessor)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            //跨域
            app.UseCors("AllowCors");
            //app.UseAuthorization();

            #region 授权验证中间件
            app.UseMiddleware<TokenAuth>();
            #endregion
            #region Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                //遍历展示版本
                foreach (var description in provider.ApiVersionDescriptions)
                {
                    c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", $"西联CRM项目接口文档{description.GroupName.ToUpperInvariant()}");
                }
                c.RoutePrefix = string.Empty;//默认访问swagger下的index.html
            });

            #endregion
            //捕获异常
            // app.UseMiddleware<ExceptionMiddleware>();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
